/*
 * @Author: wangwei wwdqq7@qq.com
 * @Date: 2025-04-01 14:30:00
 * @LastEditors: wangwei wwdqq7@qq.com
 * @LastEditTime: 2025-04-01 14:30:00
 * @FilePath: /FullStack/pro/typeorm-mysql/src/user/role.service.ts
 * @Description: 角色服务，提供角色管理的业务逻辑
 */
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

import { Permission } from '@/entity/Permission';
import { Role } from '@/entity/Role';
import { RolePermission } from '@/entity/RolePermission';
import { User } from '@/entity/User';
import { UserRole } from '@/entity/UserRole';

@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(Role)
    private roleRepository: Repository<Role>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
    @InjectRepository(Permission)
    private permissionRepository: Repository<Permission>,
    @InjectRepository(UserRole)
    private userRoleRepository: Repository<UserRole>,
    @InjectRepository(RolePermission)
    private rolePermissionRepository: Repository<RolePermission>,
  ) {}

  async getRoles() {
    try {
      const roles = await this.roleRepository.find();
      return {
        code: 0,
        data: roles,
        msg: '获取角色列表成功',
      };
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : '未知错误';
      return {
        code: 1,
        data: [],
        msg: `获取角色列表失败: ${errMsg}`,
      };
    }
  }

  async getRoleById(id: number) {
    try {
      const role = await this.roleRepository.findOne({ where: { id } });
      if (!role) {
        throw new NotFoundException(`ID为${id}的角色不存在`);
      }
      return {
        code: 0,
        data: role,
        msg: '获取角色成功',
      };
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : '未知错误';
      return {
        code: 1,
        data: null,
        msg: errMsg,
      };
    }
  }

  async createRole(roleData: Partial<Role>) {
    try {
      const newRole = this.roleRepository.create(roleData);
      const savedRole = await this.roleRepository.save(newRole);
      return {
        code: 0,
        data: savedRole,
        msg: '创建角色成功',
      };
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : '未知错误';
      return {
        code: 1,
        data: null,
        msg: `创建角色失败: ${errMsg}`,
      };
    }
  }

  async updateRole(id: number, roleData: Partial<Role>) {
    try {
      const role = await this.roleRepository.findOne({ where: { id } });
      if (!role) {
        throw new NotFoundException(`ID为${id}的角色不存在`);
      }

      await this.roleRepository.update(id, roleData);
      const updatedRole = await this.roleRepository.findOne({ where: { id } });

      return {
        code: 0,
        data: updatedRole,
        msg: '更新角色成功',
      };
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : '未知错误';
      return {
        code: 1,
        data: null,
        msg: `更新角色失败: ${errMsg}`,
      };
    }
  }

  async deleteRole(id: number) {
    try {
      const role = await this.roleRepository.findOne({ where: { id } });
      if (!role) {
        throw new NotFoundException(`ID为${id}的角色不存在`);
      }

      await this.roleRepository.delete(id);
      return {
        code: 0,
        data: null,
        msg: '删除角色成功',
      };
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : '未知错误';
      return {
        code: 1,
        data: null,
        msg: `删除角色失败: ${errMsg}`,
      };
    }
  }

  async getRoleUsers(id: number) {
    try {
      const role = await this.roleRepository.findOne({ where: { id } });
      if (!role) {
        throw new NotFoundException(`ID为${id}的角色不存在`);
      }

      const userRoles = await this.userRoleRepository.find({
        where: { RoleId: id },
        relations: ['user'],
      });

      const users = userRoles.map((ur) => ur.user);

      return {
        code: 0,
        data: users,
        msg: '获取拥有该角色的用户成功',
      };
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : '未知错误';
      return {
        code: 1,
        data: [],
        msg: `获取拥有该角色的用户失败: ${errMsg}`,
      };
    }
  }

  async getRolePermissions(id: number) {
    try {
      const role = await this.roleRepository.findOne({ where: { id } });
      if (!role) {
        throw new NotFoundException(`ID为${id}的角色不存在`);
      }

      const rolePermissions = await this.rolePermissionRepository.find({
        where: { RoleId: id },
        relations: ['permission'],
      });

      const permissions = rolePermissions.map((rp) => rp.permission);

      return {
        code: 0,
        data: permissions,
        msg: '获取角色权限成功',
      };
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : '未知错误';
      return {
        code: 1,
        data: [],
        msg: `获取角色权限失败: ${errMsg}`,
      };
    }
  }

  async assignPermissionToRole(roleId: number, permissionId: number) {
    try {
      // 检查角色和权限是否存在
      const role = await this.roleRepository.findOne({ where: { id: roleId } });
      if (!role) {
        throw new NotFoundException(`ID为${roleId}的角色不存在`);
      }

      const permission = await this.permissionRepository.findOne({
        where: { id: permissionId },
      });
      if (!permission) {
        throw new NotFoundException(`ID为${permissionId}的权限不存在`);
      }

      // 检查是否已经分配过该权限
      const existingRolePermission =
        await this.rolePermissionRepository.findOne({
          where: { RoleId: roleId, PermissionId: permissionId },
        });

      if (existingRolePermission) {
        return {
          code: 0,
          data: existingRolePermission,
          msg: '该权限已分配给角色',
        };
      }

      // 创建新的角色权限关联
      const rolePermission = this.rolePermissionRepository.create({
        RoleId: roleId,
        PermissionId: permissionId,
        role,
        permission,
      });

      await this.rolePermissionRepository.save(rolePermission);

      return {
        code: 0,
        data: rolePermission,
        msg: '权限分配成功',
      };
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : '未知错误';
      return {
        code: 1,
        data: null,
        msg: `权限分配失败: ${errMsg}`,
      };
    }
  }

  async removePermissionFromRole(roleId: number, permissionId: number) {
    try {
      const rolePermission = await this.rolePermissionRepository.findOne({
        where: { RoleId: roleId, PermissionId: permissionId },
      });

      if (!rolePermission) {
        throw new NotFoundException(
          `未找到角色ID为${roleId}和权限ID为${permissionId}的关联`,
        );
      }

      await this.rolePermissionRepository.remove(rolePermission);

      return {
        code: 0,
        data: null,
        msg: '移除权限成功',
      };
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : '未知错误';
      return {
        code: 1,
        data: null,
        msg: `移除权限失败: ${errMsg}`,
      };
    }
  }
}
